package cn.sc.summer.mybatis.config;

import cn.hutool.core.text.CharSequenceUtil;
import cn.sc.summer.mybatis.annotation.dynamicdatasource.MapperScanner;
import cn.sc.summer.mybatis.annotation.dynamicdatasource.MapperSource;
import cn.sc.summer.mybatis.enums.DataSourceEnum;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.reflections.util.ConfigurationBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author a-xin
 * @className MybatisPlusConfig
 * @date 2022-04-29 14:55
 */
@Slf4j
@Configuration
@MapperScanner(basePackages = "${mybatis-plus.mapper-scan}")
public class MyBatisPlusConfig {

    public static final String MAPPER_SOURCE_BEAN_NAME = "MAPPER_SOURCE_BEAN_NAME";

    @Value(value = "${mybatis-plus.mapper-scan}")
    private String[] BASE_PACKAGES;

    @Bean(name = MAPPER_SOURCE_BEAN_NAME)
    public Map<String, String> mapperSourceMap() {
        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .forPackages(BASE_PACKAGES));
        Set<Class<?>> mapperSourceClass = reflections.getTypesAnnotatedWith(MapperSource.class);
        Map<String, String> mapperSourceMap = new HashMap<>();
        mapperSourceClass.stream().forEach(item -> {
            MapperSource mapperSource = item.getAnnotation(MapperSource.class);
            DataSourceEnum value = mapperSource.value();
            String target = mapperSource.target();
            if (CharSequenceUtil.isNotBlank(target)) {
                mapperSourceMap.put(item.getName(), target);
            } else {
                mapperSourceMap.put(item.getName(), value.getType());
            }
        });
        return mapperSourceMap;
    }

}
